package com.educate.device.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.device.dao.DeviceMessageDao;
import com.educate.device.model.bo.DeviceMessageBO;
import com.educate.device.model.po.DeviceMessage;
import com.educate.device.rpc.api.DeviceMessageService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class DeviceMessageServiceImpl implements DeviceMessageService {

    @Resource DeviceMessageDao deviceMessageDao;

    @Override
    public void create(DeviceMessageBO bo) {
        deviceMessageDao.insert(bo);
    }

    @Override
    public void delete(DeviceMessageBO bo) {
        deviceMessageDao.delete(bo);
    }

    @Override
    public void delete(String deviceMessageId) {
        deviceMessageDao.deleteById(deviceMessageId);
    }

    @Override
    public DeviceMessageBO detail(String deviceMessageId) {
        Optional<DeviceMessage> optional = deviceMessageDao.findById(deviceMessageId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new DeviceMessageBO(optional.get());
    }

    @Override
    public DeviceMessageBO detail(DeviceMessageBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(DeviceMessageBO bo) {
        Optional<DeviceMessage> optional = deviceMessageDao.findById(bo.getDeviceMessageId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        deviceMessageDao.save(optional.get());
    }

    @Override
    public Page<DeviceMessageBO> query(DeviceMessageBO bo, PageRequest pageRequest) {
        return deviceMessageDao.query(bo, pageRequest).map(DeviceMessageBO::new);
    }

    @Override
    public List<DeviceMessageBO> list(DeviceMessageBO bo) {
        List<DeviceMessage> result = deviceMessageDao.findAll();
        return ListUtils.map(result, DeviceMessageBO::new);
    }
}
